<template>
  <div>
    <a-upload
      v-model:file-list="fileList"
      action="/api/image/upload"
      list-type="picture-card"
      @preview="handlePreview"
      @change="onChange"
      accept="image/*"
      :max-count="1"
      @remove="onRemove"
    >
      <div v-if="fileList.length < 8">
        <plus-outlined />
        <div style="margin-top: 8px">上传图片</div>
      </div>
    </a-upload>
    <a-modal
      v-model:open="previewVisible"
      :title="previewTitle"
      :footer="null"
      @cancel="handleCancel"
    >
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { PlusOutlined } from '@ant-design/icons-vue'
import { ref } from 'vue'

const props = defineProps<{
  id: string | null
}>()
const emits = defineEmits(['update:id'])
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const fileList = ref<any[]>([])

watch(
  () => props.id,
  (v) => {
    fileList.value = v ? [{ id: v, url: `/api/image/0/150/${v}` }] : []
  },
  { immediate: true },
)
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}
const handlePreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}
const onChange = ({ file }: any) => {
  if (file.status === 'done') {
    emits('update:id', file.response.data.id)
  }
}
const onRemove = () => {
  emits('update:id', null)
}
</script>

<style scoped></style>
